<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<x-back-btn></x-back-btn>
				<view class="u-f-40 common-title">{{ lang_common.setting }}</view>
				<view></view>
			</view>
			<!-- 分割线 -->
			<u-gap height="1" bgColor="rgba(0, 0, 0, 0.07)"></u-gap>
		</view>

		<!-- 内容 -->
		<view>
			<view v-for="(list, lindex) in navs" :key="lindex" :class="['bg-white', lindex > 0 ? 'u-m-t-12' : '']">
				<view v-for="(item, index) in list" :key="index" style="padding: 0 16rpx 0 0;">
					<view :style="{
						borderTop: `${ index > 0 ? 2 : 0 }rpx solid #f9f9f9`
					}" class="flex-center-between u-p-24" @click="changeAction(item)">
						<view class="flex-center">
							<image :src="item.icon" style="width: 40rpx; height: 40rpx" class="clear-flex"></image>
							<view class="u-m-l-14 u-f-34 u-lh-48 linecamp-1">{{ lang_setting[item.labelKey || item.key] }}</view>
						</view>

						<view class="flex-center">
							<view v-if="item.key === 'clear'" class="u-m-r-10 u-f-30 u-lh-42 color-grew">
								{{ storageFormat }}
							</view>
							<view v-else-if="typeof item.format === 'function' || item.tipsKey"
								class="u-m-r-10 u-f-30 u-lh-42 color-grew">
								{{ item.tipsKey && (lang_setting[item.tipsKey]) || item.format() }}
							</view>
							<image src="@/static/image/common/arrow_right.png" style="width: 12rpx; height: 20rpx;"
								class="clear-flex"></image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<x-fixed-bottom background="rgba(0,0,0,0)">
			<view class="flex-center-center" style="padding-bottom: 90rpx;">
				<x-common-btn width="502" height="82" background="#FD1E43" @click="logoutVisible = true">
					<view class="u-f-32 u-lh-44 font-medio">{{ lang_setting.logout }}</view>
				</x-common-btn>
			</view>
		</x-fixed-bottom>

		<!-- 注销账号 -->
		<u-modal v-model="destroyVisible" :show-title="false" :content="lang_setting.destoryTips" show-cancel-button
			:cancel-text="lang_setting.cancelDestory"
			:confirm-text="lang_setting.confirmDestory + (destroyTime > 0 ? `(${destroyTime}S)` : '')"
			:confirm-color="!destroyTime ? '#FD1E43' : '#999999'" async-close ref="uModal"
			@confirm="confirmDestoryAction" z-index="9999999">
		</u-modal>
		<!-- 退出登录 -->
		<u-modal v-model="logoutVisible" :show-title="false" :content="lang_setting.logoutTips" show-cancel-button
			:cancel-text="lang_setting.cancelLogout" :confirm-text="lang_setting.confirmLogout"
			:confirm-color="'#FD1E43'" @confirm="logoutAction" z-index="9999999">
		</u-modal>
		<!-- 清空缓存 -->
		<u-modal v-model="storageVisible" :show-title="false" :content="lang_setting.storageTips" show-cancel-button
			:cancel-text="lang_setting.cancelStorage" :confirm-text="lang_setting.confirmStorage"
			:confirm-color="'#FD1E43'" @confirm="storageAction" z-index="9999999">
		</u-modal>
	</view>
</template>

<script>
	import {
		Logout
	} from '@/api/base.js'
	import { userDestroy } from '@/api/personal.js'
	import {
		TOKENNAME,
		USER_INFO,
		USER_TYPE,
		APP_LANG
	} from '@/config.js'
	import storage from '@/storage.js'

	let formatNumber = (number) => {
		let BASE = 1024;
		if (number < 1024) {
			return number + "B";
		} else if (number < (BASE * BASE)) {
			return (number / BASE).toFixed(2) + "KB";
		} else if (number < (BASE * BASE * BASE)) {
			return (number / (BASE * BASE)).toFixed(2) + "MB";
		} else {
			return (number / (BASE * BASE * BASE)).toFixed(2) + "GB";
		}
	}
	export default {
		data() {
			// 获取版本信息
			const version = () => {
				return 'V1.01'
			}
			// 初始化导航
			let navs = [
				[{
						key: 'account',
						label: '账号与安全',
						page: '/pages/user/setting/account/index/index'
					},
					// {
					// 	key: 'notice',
					// 	label: '新消息通知',
					// 	page: '/pages/user/setting/notice/notice'
					// },
					// {
					// 	key: 'privacy',
					// 	label: '隐私设置',
					// 	page: '/pages/other/richText/richText?type=privacy'
					// },
				],
				[{
						key: 'clear',
						label: '清除缓存',
						page: '',
						format: () => '0B'
					},
					// {
					// 	key: 'update',
					// 	label: '版本更新',
					// 	page: '',
					// 	format: () => version()
					// },
				],
				[
					{
					key: 'update',
					labelKey: 'transformLanguage',
					label: '中西翻译',
					page: ''
				},
				 {
				 	key: 'about',
				 	label: '关于我们',
				 	page: '/pages/user/setting/about/about'
				 },],
				[{
					key: 'close',
					label: '注销账号',
					page: '',
					tipsKey: 'closeTips'
				}, ]
			].map(list => list.map(item => {
				let result = {
					...item,
					icon: require(`@/static/image/setting/${ item.key }@2x.png`)
				}
				return result
			}))
			return {
				navs,
				destroyVisible: false,
				destroyTime: 5,
				timer: null,

				logoutVisible: false,
				storageSize: 0,
				storageVisible: false
			}
		},
		computed: {
			storageFormat() {
				return formatNumber(this.storageSize)
			}
		},
		created() {
			this.initStorage()
		},
		methods: {
			changeAction(item) {
				const {
					page,
					key
				} = item
				if (page) {
					this.jumpUrl(page)
				} else if (key === 'close') {
					this.destroyVisible = true

					this.destroyTime = 5
					clearInterval(this.timer)
					this.timer = setInterval(() => {
						this.destroyTime--
						if (!this.destroyTime) {
							clearInterval(this.timer)
						}
					}, 1000)
				} else if (key === 'clear') {
					if (!this.storageSize) {
						this.$api.msg(this.lang_setting.storageUnClearTips)
					} else {
						this.storageVisible = true
					}
				} else if (key === 'update') {
					uni.setStorageSync(APP_LANG, uni.getStorageSync(APP_LANG) === 'zh' ? 'es' : 'zh')
					plus.runtime.restart()
				}
			},
			// 执行注销操作
			confirmDestoryAction() {
				this.$refs.uModal.clearLoading();
				if (!this.destroyTime) {
					this.destroyTime = -1
					
					userDestroy({}).then(() => {
						let timer = setTimeout(() => {
							this.destroyVisible = false
						}, 1000)
					})
				}
			},
			async initStorage() {
				let storageSize = 0;
				// 计算缓存
				let systemCach = await new Promise(resolve => {
					plus.cache.calculate((size) => {
						let sizeCache = parseInt(size);
						resolve(sizeCache)
					});
				})
				this.$set(this, 'storageSize', (systemCach + storageSize))
			},
			clearCache() {
				return new Promise(resolve => {
					let os = plus.os.name;
					if (os == 'Android') {
						let main = plus.android.runtimeMainActivity();
						let sdRoot = main.getCacheDir();
						let files = plus.android.invoke(sdRoot, "listFiles");
						let len = files.length;
						for (let i = 0; i < len; i++) {
							let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
							plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
								if (entry.isDirectory) {
									entry.removeRecursively((entry) => { //递归删除其下的所有文件及子目录  
										uni.showToast({
											title: '缓存清理完成',
											duration: 2000
										});
										this.initStorage(); // 重新计算缓存  
									}, (e) => {
										console.log(e.message)
									});
								} else {
									entry.remove();
								}
							}, (e) => {
								console.log('文件路径读取失败')
							});
						}
					} else { // ios  
						plus.cache.clear(function() {
							uni.showToast({
								title: '缓存清理完成',
								duration: 2000
							});
							this.initStorage()
						});
					}
				})
			},
			storageAction() {
				// 清楚缓存
				for (let key in storage) {
					uni.removeStorageSync(storage[key])
				}
				this.clearCache()
			},
			logoutAction() {
				this.logoutVisible = false
				uni.removeStorageSync(APP_LANG)
				Logout({}).then((result) => {
					uni.hideToast()
					this.$store.commit('UPDATE_USER_INFO', {})
					uni.reLaunch({
						url: '/pages/first/select/select'
					})
				}).finally(() => {
					uni.hideToast()
					uni.reLaunch({
						url: '/pages/first/select/select'
					})
				})
			}
		}
	}
</script>

<style scoped lang="scss">

</style>
